﻿using ASDL;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace _163News
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            #region 初始化lvw_channel

            // 定义委托方法
            Action<string, string> JoinUrl2Lvw = (groupName, txt) =>
            {
                MatchCollection mc = Regex.Matches(txt, "(.*?)  (.*)");
                ListViewGroup group1 = new ListViewGroup(groupName);
                lvw_channel.Groups.Add(group1);
                foreach (Match m in mc)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = m.Groups[1].Value;
                    item.SubItems.Add(m.Groups[2].Value);
                    item.Group = group1;
                    lvw_channel.Items.Add(item);
                }
            };
            // 加入 频道链接
            JoinUrl2Lvw("频道链接", Resource1.Channel);

            // 加入 滚动新闻链接
            JoinUrl2Lvw("滚动新闻链接", Resource1.RollingNews);

            #endregion 初始化lvw_channel
        }

        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in lvw_channel.Items)
            {
                item.Checked = true;
            }
        }

        private void 反选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in lvw_channel.Items)
            {
                item.Checked = !item.Checked;
            }
        }

        /// <summary>
        /// 宽带连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_bdConn_Click(object sender, EventArgs e)
        {
            ASDLHelper a = new ASDLHelper(txt_bdName.Text, txt_bdUser.Text, txt_bdPwd.Text);
            if (a.Connect() == 0)
            {
                MessageBox.Show(this, "连接成功");
            }
            else
            {
                MessageBox.Show(this, "连接失败");
            }
        }

        /// <summary>
        /// 宽带断开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_bdDisConn_Click(object sender, EventArgs e)
        {
            ASDLHelper a = new ASDLHelper(txt_bdName.Text, txt_bdUser.Text, txt_bdPwd.Text);
            a.Disconnect();
        }

        private void btn_reConn_Click(object sender, EventArgs e)
        {
            ASDLHelper a = new ASDLHelper(txt_bdName.Text, txt_bdUser.Text, txt_bdPwd.Text);
            a.Disconnect();
            if (a.Connect() == 0)
            {
                MessageBox.Show(this, "连接成功");
            }
            else
            {
                MessageBox.Show(this, "连接失败");
            }
        }

        private enum Lvw_userInfoColumns
        {
            ID = 0,
            User = 1,
            Pwd = 2,
            Cookies = 3,
        }
        private enum Lvw_channelColumns
        {
            Name = 0,
            Url = 1,
        }
        private enum Lvw_log
        {
            ID = 0,
            Name = 1,
            Value = 2,
        }
        
        private void tsb_beginLogin_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem((count) =>
            {
                for (int i = 0; i < (int)count; i++)
                {
                    // 获取item
                    ListViewItem item = (ListViewItem)this.Invoke((Func<ListViewItem>)delegate { return lvw_userInfo.Items[i]; });

                    if (!string.IsNullOrEmpty(item.SubItems[(int)Lvw_userInfoColumns.Cookies].Text)) continue;
                    string user = item.SubItems[(int)Lvw_userInfoColumns.User].Text;
                    string pwd = item.SubItems[(int)Lvw_userInfoColumns.Pwd].Text;
                    _163NewsWebProtocol news = new _163NewsWebProtocol();
                    news.Login(user, pwd);

                    this.Invoke((EventHandler)delegate
                    {
                        // 显示cookie
                        item.SubItems[(int)Lvw_userInfoColumns.Cookies].Text = news.Cookie;

                        lvw_userInfo.Items[i].EnsureVisible();
                    });
                }
            }, lvw_userInfo.Items.Count);
        }

        private void tsb_importUser_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() != DialogResult.OK) return;
            // 初始化lvw_userInfo
            lvw_userInfo.Items.Clear();

            string[] lines = File.ReadAllLines(ofd.FileName);
            foreach (string line in lines)
            {
                string[] arr = Regex.Split(line, "-{4}");
                if (arr.Length != 2) continue;
                string user = arr[0];
                string pwd = arr[1];
                ListViewItem item = new ListViewItem();
                item.Text = (lvw_userInfo.Items.Count + 1).ToString();
                item.SubItems.Add(user);
                item.SubItems.Add(pwd);
                item.SubItems.Add(string.Empty);//cookie
                lvw_userInfo.Items.Add(item);
            }
        }

        private void txt_bdStepLogin_TextChanged(object sender, EventArgs e)
        {
            int res;
            if (!Int32.TryParse(this.txt_bdStepLogin.Text, out res))
            {
                this.txt_bdStepLogin.Text = null;
            }
        }

        /// <summary>
        /// 开始评论
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_beginComment_Click(object sender, EventArgs e)
        {
            #region 初始化组件

            btn_beginComment.Enabled = !btn_beginComment.Enabled;

            #endregion 初始化组件

            #region 初始化数据

            // 读取评论内容
            string[] commentLines = null;
            try
            {
                commentLines = File.ReadAllLines(txt_commentFilePath.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "读取文件异常");
                return;
            }

            // 读取账号Cookie
            List<string> cookies = new List<string>();
            foreach (ListViewItem item in lvw_userInfo.Items)
            {
                string cookie = item.SubItems[(int)Lvw_userInfoColumns.Cookies].Text;
                if (!string.IsNullOrEmpty(cookie)) cookies.Add(cookie);
            }

            // 读取要评论的频道信息
            List<string> channels = new List<string>();
            foreach (ListViewItem item in lvw_channel.Items)
            {
                if(item.Checked)
                {
                    string channel = item.SubItems[(int)Lvw_channelColumns.Url].Text;
                    channels.Add(channel);
                }
            }

            // 读取设置信息
            int bdStepByUser = Convert.ToInt32(nud_bdStepByUserByComment.Value);
            int commentNumByUser = Convert.ToInt32(nud_commentNumByUser.Value);
            int commentNumByChannels = Convert.ToInt32(nud_commentNumByChannels.Value);
            ASDLHelper asdl = new ASDLHelper(txt_bdName.Text, txt_bdUser.Text, txt_bdPwd.Text);
            #endregion 初始化数据


            ThreadPool.QueueUserWorkItem((o) => 
            {
                int userIndex = 0;
                int commentLinesIndex = 0;
                foreach (string channel in channels)
                {
                    List<string> news = _163NewsWebProtocol.CollectNewsUrl(channel);
                    foreach(string newUrl in news)
                    {
                        _163NewsWebProtocol _163News = new _163NewsWebProtocol();
                        _163News.Cookie = cookies[userIndex++];
                        // 判断userIndex是否越界
                        if (userIndex >= cookies.Count) userIndex = 0;

                        string commentValue = commentLines[commentLinesIndex++];
                        bool commentRes = _163News.Comment(newUrl, commentValue);
                        // 判断commentLinesIndex是否越界
                        if (commentLinesIndex >= commentLines.Length) commentLinesIndex = 0;

                        // 加入lvw_log
                        this.Invoke((EventHandler)delegate 
                        {
                            ListViewItem item = new ListViewItem();
                            item.Text = (lvw_log.Items.Count + 1).ToString();
                            item.SubItems.Add(newUrl);
                            item.SubItems.Add(commentValue);
                            lvw_log.Items.Add(item);
                        });

                        // 判断是否需要拨号
                        if(userIndex % bdStepByUser == 0)
                        {
                            asdl.Disconnect();
                            asdl.Connect();
                        }
                    }
                }

                // 还原组件
                this.Invoke((EventHandler)delegate
                {
                    btn_beginComment.Enabled = !btn_beginComment.Enabled;
                });

                });

        }

        private void btn_openComment_Click(object sender, EventArgs e)
        {
            OpenFileDialog o = new OpenFileDialog();
            o.Filter = "文本文件|*.txt";
            if (o.ShowDialog() != DialogResult.OK) return;
            txt_commentFilePath.Text = o.FileName;
        }


        private void lvw_log_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            string url = lvw_log.SelectedItems[0].SubItems[1].Text;
            Process.Start(url);
        }
    }
}